package com.treeman.api.controller;

import org.apache.log4j.Logger;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.treeman.api.security.ApiAuthenticationManager;
import com.treeman.api.security.context.AccessTokenAuthenticationToken;

@RequestMapping(value = "/api")
@Controller
public class ApiLogoutController extends ApiExceptionResolverController {

	private static Logger log = Logger.getLogger(ApiLogoutController.class);

	@RequestMapping(value = "/apilogout", method = RequestMethod.POST)
	@PreAuthorize("isAuthenticated() and #username == authentication.name")
	public @ResponseBody
	void logout(
			@RequestParam(value = "username", required = true) String username) {

		Authentication authentication = SecurityContextHolder.getContext()
				.getAuthentication();

		if (authentication instanceof AccessTokenAuthenticationToken) {
			String accessToken = authentication.getName();

			ApiAuthenticationManager.getInstance().invalidateUserAccessToken(
					accessToken, username);
			log.debug("User has been logged out.");
		}
	}

}
